package com.notice.rule;

import com.google.common.collect.Lists;
import com.notice.config.LogSpringContent;

import java.util.List;
import java.util.Map;


/**
 * 错误通知规则工厂
 *
 * @Author dzl
 * @Date 2022/1/4 2:40 下午
 */
public class LogNoticeRuleFactory {
    private volatile static LogErrorNoticeRule errorRule;
    private static final Object LOCK = new Object();
    private static final String DEFAULT_BEAN = DefaultLogErrorNoticeRule.class.getSimpleName();
    private static final List<LogErrorNoticeRule> RULES = Lists.newArrayListWithCapacity(2);

    /**
     * 消息匹配规则
     */
    public static void getLogErrorNoticeRule() {
        if (errorRule == null) {
            synchronized (LOCK) {
                if (errorRule == null) {
                    init();
                }
            }
        }
    }

    /**
     * 是否发送这条警告
     *
     * @param exceptionClassName 异常的类名
     * @param msg                错误信息
     * @return true通过
     */
    public static Boolean matchRule(String exceptionClassName, String msg) {
        boolean result = true;
        for (LogErrorNoticeRule rule : RULES) {
            if (result) {
                result = rule.matchRule(exceptionClassName, msg);
            } else {
                return false;
            }
        }
        return result;
    }

    /**
     * 初始化
     */
    private static void init() {
        Map<String, LogErrorNoticeRule> beansOfType = LogSpringContent.getApplicationContext().getBeansOfType(LogErrorNoticeRule.class);
        RULES.add(beansOfType.get(DEFAULT_BEAN));
        /*自定义实现了规则*/
        if (beansOfType.size() > 1) {
            /*如果有很多的实现，默认取第一个*/
            for (String key : beansOfType.keySet()) {
                if (!DEFAULT_BEAN.equals(key)) {
                    errorRule = beansOfType.get(key);
                    RULES.add(errorRule);
                    return;
                }
            }
        } else {
            /*加载默认规则*/
            errorRule = beansOfType.get(DEFAULT_BEAN);
        }

    }
}
